package com.juyu.miliao.api.service.Activity;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.dao.mysql.*;
import com.juyu.miliao.api.dao.redis.SanGuoGameActivityRedisDao;
import com.juyu.miliao.api.dao.redis.StatisticsSummerActivityRedisDao;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.ActivityRewardLog;
import com.juyu.miliao.api.domain.Appkey;
import com.juyu.miliao.api.domain.SanGuoGameActivity;
import com.juyu.miliao.api.domain.UserWallet;
import com.juyu.miliao.api.domain.vo.*;
import com.juyu.miliao.api.service.AppKeyService;
import com.juyu.miliao.api.service.cache.ActiveGameRewardCacheService;
import com.juyu.miliao.api.util.ActivityRewardLogBuilder;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.common.constant.BeansType;
import com.juyu.miliao.common.domain.BillDetailBeans;
import com.juyu.miliao.common.domain.SanGuoGameRankingList;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  三国活动service
 * @Auther: 卜加超
 * @Date: 2019/8/6 18:48
 * @Description:
 */
@Service
@Slf4j
public class SanGuoGameActivityService {
    private static final String TIME_KEY = "coolSummerActivities";
    private static final List<String> sanGuoGameRankingRewardList = new ArrayList<>();
    private static final Map<Integer,Long> sanGuoRewardMap = new HashMap<>();
    static {
        sanGuoGameRankingRewardList.add("158万");
        sanGuoGameRankingRewardList.add("108万");
        sanGuoGameRankingRewardList.add("52万");
        sanGuoGameRankingRewardList.add("40万");
        sanGuoGameRankingRewardList.add("24万");
        sanGuoGameRankingRewardList.add("12万");
        sanGuoGameRankingRewardList.add("8万");
        sanGuoGameRankingRewardList.add("6万");
        sanGuoRewardMap.put(0,1580000L);
        sanGuoRewardMap.put(1,1080000L);
        sanGuoRewardMap.put(2,520000L);
        sanGuoRewardMap.put(3,400000L);
        sanGuoRewardMap.put(4,240000L);
        sanGuoRewardMap.put(5,120000L);
        sanGuoRewardMap.put(6,80000L);
        sanGuoRewardMap.put(7,60000L);
    }
    @Resource
    private ActiveGameRewardCacheService activeGameRewardCacheService;
    @Resource
    private SanGuoGameActivityRedisDao sanGuoGameActivityRedisDao;
    @Resource
    private AppKeyService appKeyService;
    @Resource
    private SanGuoGameActivityDao sanGuoGameActivityDao;
    @Resource
    private UserWalletDao userWalletDao;
    @Resource
    private BillDetailDao billDetailDao;
    @Resource
    private ActivityRewardLogDao activityRewardLogDao;
    @Resource
    private SanGuoGameRankingListDao sanGuoGameRankingListDao;
    @Resource
    private UserInfoCache userInfoCache;
    @Resource
    private StatisticsSummerActivityRedisDao statisticsSummerActivityRedisDao;


    /**
     * 三国活动奖励列表和个人当天赢取的寻豆数
     * @param userId
     * @return
     */
    public JSONObject getSanGuoGameActivityList(long userId) {
       List<SanGuoGameActivity> activeGameRewardList = activeGameRewardCacheService.getSanGuoGameActivityList();
       List<SanGuoGameActivityVo> list = new ArrayList<>();
       //获取用户当天盈利寻豆数
        long sanGuoGameWinBeans = sanGuoGameActivityRedisDao.getSanGuoGameWinBeans(LocalDate.now(), userId);
        for (SanGuoGameActivity sanGuoGameActivity:activeGameRewardList){
            SanGuoGameActivityVo  sanGuoGameActivityVo = new SanGuoGameActivityVo();
            BeanUtils.copyProperties(sanGuoGameActivity,sanGuoGameActivityVo);
            if(sanGuoGameActivity.getAwardLimit() <= sanGuoGameWinBeans){

                if(!sanGuoGameActivityRedisDao.checkIsGiveBeans(LocalDate.now(),userId,sanGuoGameActivity.getId())){
                    sanGuoGameActivityVo.setStatus(1);
                }else {
                    sanGuoGameActivityVo.setStatus(2);
                }
            }else {
                sanGuoGameActivityVo.setStatus(0);
            }
            list.add(sanGuoGameActivityVo);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list",list);
        if(sanGuoGameWinBeans>0){
            jsonObject.put("userTodayWinBeans",sanGuoGameWinBeans);
        }else {
            jsonObject.put("userTodayWinBeans",0);
        }
       return jsonObject;
    }

    /**
     * 领取三国活动奖励
     * @param userId
     * @param sanGuoActiveId
     */
    public void getSanGuoRewards(long userId, int sanGuoActiveId) {
        Appkey appkey = appKeyService.getAppKeyByKey(TIME_KEY);

        LocalDate localDate = LocalDate.now();

        if (appkey != null) {
            /**
             * 获取活动时间
             */
            JSONObject json = JSONObject.parseObject(appkey.getValue());

            String startDateTarget = json.getString("startDate");

            String endDateTarget = json.getString("endDate");

            LocalDate startDate = LocalDate.parse(startDateTarget,
                    DateTimeFormatter.ofPattern("yyyy-MM-dd"));

            LocalDate endDate = LocalDate.parse(endDateTarget,
                    DateTimeFormatter.ofPattern("yyyy-MM-dd"));


            if (DateUtil.checkBetweenTime(startDate, endDate, localDate)) {
                SanGuoGameActivity sanGuoGameActivity =  sanGuoGameActivityDao.getSanGuoGameActivityById(sanGuoActiveId);

                long sanGuoGameWinBeans = sanGuoGameActivityRedisDao.getSanGuoGameWinBeans(LocalDate.now(), userId);

                if (sanGuoGameWinBeans >= sanGuoGameActivity.getAwardLimit().doubleValue()) {

                    long num = sanGuoGameActivityRedisDao.setIsGiveBeans(localDate,userId,sanGuoActiveId);
                    if (num == 1) {
                        //用户没有领取过三国奖励进行领取
                        try {
                            saveSanGuoRewardsInfo(userId, sanGuoGameActivity.getAwardBeans(), localDate,sanGuoActiveId);
                        } catch (Exception ex) {
                            sanGuoGameActivityRedisDao.removeUserGetSanGuoRewards(userId, localDate, sanGuoActiveId);
                            log.error("领取三国奖励错误回滚redis:userId=[{}],sanGuoActiveId=[{}],day=[{}]",
                                    userId, sanGuoActiveId, localDate);
                            log.error("领取三国奖励错误:ex={}", ex.getMessage());
                        }
                    }else {
                        throw new ConsumeRuntimeException("请勿重复领取");
                    }
                }else {
                    throw new ConsumeRuntimeException("没有达到领取资格");
                }
            }else{
                throw new ConsumeRuntimeException("活动已过期");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveSanGuoRewardsInfo(long userId, Long awardBeans, LocalDate localDate, int sanGuoActiveId) {
        //添加用户寻豆
         int flag = userWalletDao.addBeans(userId, awardBeans);
         if(flag==1){
             //记入寻豆账单
             BillDetailBeans billDetailBeans = new BillDetailBeans();
             billDetailBeans.setBeansType(BeansType.GAME_REWARD_GIVE_BEANS.getCode());
             billDetailBeans.setBeans(awardBeans);
             billDetailBeans.setRatio(0);
             billDetailBeans.setUserId(userId);
             billDetailDao.insertBillDetailBeans(billDetailBeans);
             //记入领奖记录
             ActivityRewardLogBuilder builder = new ActivityRewardLogBuilder();

             ActivityRewardLog activityRewardLog = builder.userId(userId).deposit(0)
                     .beans(awardBeans).type(2).build();
             activityRewardLogDao.insertActivityRewardLog(activityRewardLog);
             //统计用户领取三国奖励
             sanGuoGameActivityRedisDao.statisticsUserGetSanGuoRewards(userId,localDate,sanGuoActiveId);
             //统计夏季活动寻豆支出
             statisticsSummerActivityRedisDao.summerActivityExpenditureBeans(awardBeans);
             //统计夏季活动领取奖励人数
             statisticsSummerActivityRedisDao.summerActivityGetRewardsNumbers(userId);
         }
    }

    /**
     * 查询领取列表
     * @param userId
     * @param type
     * @param page
     * @param pageSize
     * @return
     */
    public List<ActivityRewardLogVO> getSanGuoRewardsLog(long userId, int type, Integer page, Integer pageSize) {
        int startNum = PageUtil.getOffset(page, pageSize);
        Map<String,Object> params = new HashMap<>(2);
        params.put("userId",userId);
        params.put("type",type);
        params.put("startNum",startNum);
        params.put("pageSize",pageSize);
        return activityRewardLogDao.getRewardsLog(params);
    }

    /**
     * 三国排行榜
     * @param userId
     * @return
     */
    public SanGuoActivitiesRankingResultVO getSanGuoRankingList(long userId) {
        SanGuoActivitiesRankingResultVO sanGuoActivitiesRankingResultVO = new SanGuoActivitiesRankingResultVO();
        SanGuoActivitiesDetailVO sanGuoActivitiesDetailVO = new SanGuoActivitiesDetailVO();
        //获取用户盈利总寻豆数
        SanGuoGameRankingList sanGuoGameRankingList =  sanGuoGameRankingListDao.getSanGuoRankingListByUserId(userId);
        if(sanGuoGameRankingList == null){
            sanGuoActivitiesDetailVO.setProfitBeans(0L);
        }else {
            sanGuoActivitiesDetailVO.setProfitBeans(sanGuoGameRankingList.getWinsBeans());
        }
        //获取排行列表
        List<SanGuoGameRankingList> rankingLists = activeGameRewardCacheService.getSanGuoGameRankingList();
        if(rankingLists.size()==0){
            return  new SanGuoActivitiesRankingResultVO();
        }
        List<SanGuoRankingListVo> list = new ArrayList<>();
        for(int i = 0;i < rankingLists.size();i++){
            SanGuoGameRankingList sanGuoGame = rankingLists.get(i);
            SanGuoRankingListVo sanGuoListVo = new SanGuoRankingListVo();
            sanGuoListVo.setEstimatedRewardsBeans(sanGuoGameRankingRewardList.get(i));
            sanGuoListVo.setProfitBeans(sanGuoGame.getWinsBeans());
            sanGuoListVo.setUserId(sanGuoGame.getUserId());
            UserCacheVo user = userInfoCache.getUserCacheInfo(sanGuoGame.getUserId());
            sanGuoListVo.setNickName(user.getNickName());
            list.add(sanGuoListVo);
            if(sanGuoGame.getUserId().longValue() == userId){
                sanGuoActivitiesDetailVO.setRanking(Integer.toString(i+1));
            }
        }
        if(StringUtils.isEmpty(sanGuoActivitiesDetailVO.getRanking())){
            sanGuoActivitiesDetailVO.setRanking("未上榜");
        }
        sanGuoActivitiesRankingResultVO.setList(list);
        sanGuoActivitiesRankingResultVO.setSanGuoActivitiesDetailVO(sanGuoActivitiesDetailVO);
       return sanGuoActivitiesRankingResultVO;
    }

    /**
     * 发放排行榜奖励方法
     */
    @Transactional(rollbackFor = Exception.class)
    public void giveUserSendBeans(){
        //获取排行列表
        List<SanGuoGameRankingList> rankingLists = activeGameRewardCacheService.getSanGuoGameRankingList();

        for(int i = 0;i < rankingLists.size();i++){
            int num =  sanGuoGameRankingListDao.updateSanGuoRankingListByUserId(rankingLists.get(i).getUserId());
            if(num == 1){
                int flag = userWalletDao.addBeans(rankingLists.get(i).getUserId(), sanGuoRewardMap.get(i));
                if(flag==1){
                    BillDetailBeans billDetailBeans = new BillDetailBeans();
                    billDetailBeans.setBeansType(BeansType.GAME_RANKING_GIVE_BEANS.getCode());
                    billDetailBeans.setBeans(sanGuoRewardMap.get(i));
                    billDetailBeans.setRatio(0);
                    billDetailBeans.setUserId(rankingLists.get(i).getUserId());
                    billDetailDao.insertBillDetailBeans(billDetailBeans);
                }
            }

        }
    }
}

